package com.weike.yuanding.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weike.yuanding.core.domain.R;
import com.weike.yuanding.dto.user.UserDTO;
import com.weike.yuanding.dto.user.UserFriendDTO;
import com.weike.yuanding.entity.SessionMessageEntity;
import com.weike.yuanding.entity.UserEntity;
import com.weike.yuanding.entity.UserFriendEntity;
import com.weike.yuanding.feign.user.VideoService;
import com.weike.yuanding.mapper.SessionMapper;
import com.weike.yuanding.mapper.UserFriendMapper;
import com.weike.yuanding.mapper.UserMapper;
import com.weike.yuanding.utils.BaseContext;
import com.weike.yuanding.utils.JwtHelper;
import com.weike.yuanding.vo.UserMessageResVo;
import com.weike.yuanding.vo.UserOnlineResVo;
import com.weike.yuanding.vo.UserSessionResVo;
import com.weike.yuanding.ws.WebsocketController;
import lombok.Data;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName: userController
 * @Author: YuanDing
 * @Date: 2025/4/1 22:12
 * @Description:
 */
@Data
@RestController
@RequestMapping("/user")
@ConfigurationProperties(prefix = "jwt.token")
public class UserController {

    private  long tokenExpiration; //有效时间,单位毫秒 1000毫秒 == 1秒

    private  String tokenSignKey;  //当前程序签名秘钥

    @Autowired
    private UserFriendMapper userFriendMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VideoService videoService;
    private static String USER_OLINE_KEY = "user:online:";
    @Autowired
    private RedisTemplate<String , String>  redisTemplate;

    @Autowired
    private MessageController messageController;

    @Autowired
    private SessionMapper sessionMapper;

    @Autowired
    private WebsocketController websocketController;

    @GetMapping("heartbeat")
    public R ping() {
        String userId = BaseContext.userId.get();
        redisTemplate.opsForValue().set(USER_OLINE_KEY + userId, "1" , 20  , TimeUnit.SECONDS);
        return R.ok();
    }


    @GetMapping("userIdList")
    public R<UserFriendDTO> guanzhuUserIdList(@RequestParam("userId") String userId) {

        List<UserFriendEntity> userFriendEntities = userFriendMapper.selectList(new LambdaQueryWrapper<UserFriendEntity>()
                .eq(UserFriendEntity::getMyUserId, userId));
        UserFriendDTO userFriendDTO = new UserFriendDTO();
        userFriendDTO.setUserIdList(userFriendEntities.stream().map(UserFriendEntity::getUserId).collect(Collectors.toList()));
        return R.ok(userFriendDTO);
    }

    @PostMapping("guanzhu")
    public R guanzhu(@RequestBody UserFriendEntity userFriendEntity) {
        if ("1".equals(userFriendEntity.getType())) {
            userFriendMapper.delete(new LambdaQueryWrapper<UserFriendEntity>()
                    .eq(UserFriendEntity :: getUserId , userFriendEntity.getUserId())
                    .eq(UserFriendEntity :: getMyUserId , userFriendEntity.getMyUserId()));
        } else {
            userFriendMapper.insert(userFriendEntity);
        }

        return R.ok();
    }

    @GetMapping("info")
    public R getUserInfo() {
        String userId = BaseContext.userId.get();
        UserEntity user = getUserInfo(userId);

        return R.ok(user);
    }

    @GetMapping("userInfo/{userId}")
    public R getUserInfoById(@PathVariable("userId") String userId) {
        UserEntity user = getUserInfo(userId);
        String userIdMy = BaseContext.userId.get();
        user.setIsGuanZhu(userFriendMapper.selectCount(
                new LambdaQueryWrapper<UserFriendEntity>()
                        .eq(UserFriendEntity :: getUserId ,userId )
                        .eq(UserFriendEntity :: getMyUserId , userIdMy)

        ) > 0);
        return R.ok(user);
    }

    private UserEntity getUserInfo(String userId) {
        UserEntity user = userMapper.selectById(userId);
        R<UserDTO> userInfoById = videoService.getUserInfoById(userId);
        user.setLikedNumber(userInfoById.getData().getLikedNumber());
        Long number1 = userFriendMapper.selectCount(new LambdaQueryWrapper<UserFriendEntity>()
                .eq(UserFriendEntity::getUserId, userId));
        user.setFenSiNumber(Integer.parseInt(number1.toString()));


        Long number2 = userFriendMapper.selectCount(new LambdaQueryWrapper<UserFriendEntity>()
                .eq(UserFriendEntity::getMyUserId, userId));
        user.setFenSiNumber(Integer.parseInt(number2.toString()));

        user.setGuanZhuNumber(userInfoById.getData().getLikedNumber());

        UserOnlineResVo userOnlineResVo = new UserOnlineResVo();
        userOnlineResVo.setOnline(true);
        userOnlineResVo.setType(1);
        userOnlineResVo.setUserId(userId);
        userOnlineResVo.setAvatar(user.getAvatar());
        userOnlineResVo.setName(user.getName());
        this.sendOnlineNoticeToUser(userOnlineResVo);
        return user;
    }

    // 给其他人发布上线通知
    @Async("taskExecutor")
    public void sendOnlineNoticeToUser(UserOnlineResVo userOnlineResVo) {
        try {
            List<UserSessionResVo> list = sessionMapper.selectListByUserId(userOnlineResVo.getUserId());
            list.forEach(item -> {
                if (item.getUserId() != null) {
                    websocketController.sendOnline(userOnlineResVo , item.getUserId());
                }
            });
        } catch (Exception e) {
            System.err.println("异步保存消息记录失败");
        }
    }

    @GetMapping("info/id")
    public R getUserInfoById(@RequestParam("userId") String userId , @RequestParam("myId") String myId ) {
        UserEntity user = userMapper.selectById(userId);

        // 是否关注
        Long l = userFriendMapper.selectCount(new LambdaQueryWrapper<UserFriendEntity>()
                .eq(UserFriendEntity::getMyUserId, myId)
                .eq(UserFriendEntity::getUserId, userId));
        user.setIsGuanZhu(l > 0);
        return R.ok(user);
    }

    @PostMapping("/login")
    public R login(@RequestBody UserEntity userEntity) {

        if (StrUtil.isNotBlank(userEntity.getPhone())
                && StrUtil.isNotBlank(userEntity.getCode())
                && "8888".equals(userEntity.getCode())) {
            JwtHelper jwtHelper = new JwtHelper();
            // 检查有无手机号
            UserEntity user = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
                    .eq(UserEntity::getPhone, userEntity.getPhone()));
            if (user != null) {
                String token = jwtHelper.createToken(user.getUserId(), tokenExpiration, tokenSignKey);
                return R.ok(token);
            } else {
                UserEntity newUser = new UserEntity();
                newUser.setName("秒友" + RandomUtil.randomNumbers(4));
                newUser.setPhone(userEntity.getPhone());
                newUser.setAvatar("https://tdesign.gtimg.com/site/avatar.jpg");
                userMapper.insert(newUser);
                return R.ok(jwtHelper.createToken(newUser.getUserId(), tokenExpiration, tokenSignKey));
            }
        }
        return R.fail("登录失败！");
    }
}
